<script setup lang="ts">
defineOptions({
  name: "infoConfirm"
});

import { ref, reactive, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { useRoute } from "vue-router";
import checkListTitle from "./checkListTitle.vue";
import dayjs from "dayjs";
import { queryAllChemicalName } from "@/api/modules/operation";

const route = useRoute();

let defaultParams = {};

interface Props {
  data: Record<string, any> | null;
  disabled?: boolean;
  onlyList?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  disabled: false,
  onlyList: false
});

const infoConfirmRef = ref<FormInstance>();
interface FormType {
  chemical: string;
  sumNum: string;
  drumANum: string;
  drumBNum: string;
  lotNumber: string;
  produceTime: string;
  validityTime: string;
  bucketCapacity: string;
}
const infoConfirmForm = reactive<FormType>({
  chemical: "",
  sumNum: "",
  drumANum: "",
  drumBNum: "",
  lotNumber: "",
  produceTime: "",
  validityTime: "",
  bucketCapacity: ""
});

const chemicalLoading = ref<boolean>(false);
const chemicalOptions = ref<Array<any>>([]);

const remoteMethod = async (searchKey: string) => {
  if (searchKey) {
    chemicalLoading.value = true;
    const res = await queryAllChemicalName({ searchKey }, () => {
      chemicalLoading.value = false;
    });
    chemicalOptions.value = res;
    chemicalLoading.value = false;
  } else {
    chemicalOptions.value = [];
  }
};

const validateNum = (rule: any, value: any, callback: any, message: string) => {
  if (!value) {
    callback(new Error(message));
  } else {
    if (infoConfirmForm.sumNum && infoConfirmForm.drumANum && infoConfirmForm.drumBNum) {
      if (Number(infoConfirmForm.sumNum) !== Number(infoConfirmForm.drumANum) + Number(infoConfirmForm.drumBNum)) {
        const msg = "注意：Drum A 与 Drum B 之和为合计数量！";
        callback(new Error(msg));
      } else {
        callback();
      }
    } else {
      callback();
    }
  }
};

const validateDate = (rule: any, value: any, callback: any, message: string) => {
  if (!value) {
    callback(new Error(message));
  } else {
    if (infoConfirmForm.produceTime && infoConfirmForm.validityTime) {
      if (dayjs(infoConfirmForm.produceTime).valueOf() > dayjs(infoConfirmForm.validityTime).valueOf()) {
        const msg = "注意：生产日期必须在有效期之前！";
        callback(new Error(msg));
      } else {
        callback();
      }
    } else {
      callback();
    }
  }
};

const infoConfirmRules = reactive<FormRules<FormType>>({
  chemical: [{ required: true, message: "请输入Chemical", trigger: ["blur"] }],
  sumNum: [{ required: true, validator: (rule, value, callback) => validateNum(rule, value, callback, "请输入合计数量"), trigger: "blur" }],
  drumANum: [{ required: true, validator: (rule, value, callback) => validateNum(rule, value, callback, "请输入Drum A"), trigger: "blur" }],
  drumBNum: [{ required: true, validator: (rule, value, callback) => validateNum(rule, value, callback, "请输入Drum B"), trigger: "blur" }],
  lotNumber: [{ required: true, message: "请输入Lot Number", trigger: ["blur"] }],
  produceTime: [{ required: true, validator: (rule, value, callback) => validateDate(rule, value, callback, "请选择生产日期"), trigger: "blur" }],
  validityTime: [{ required: true, validator: (rule, value, callback) => validateDate(rule, value, callback, "请选择有效期"), trigger: "blur" }],
  bucketCapacity: [{ required: true, message: "请输入桶容量", trigger: ["blur"] }]
});

const collapseValue = ref<Array<string>>(["信息确认"]);
const collapseTitle = ref<string>("信息确认");
const realDisabled = computed(() => props.disabled);

const disabledDateFn = (date: Date) => {
  if (dayjs().valueOf() < dayjs(date).valueOf()) {
    return true;
  } else if (!!infoConfirmForm.validityTime && dayjs(date).valueOf() > dayjs(infoConfirmForm.validityTime).valueOf()) {
    return true;
  }
  return false;
};

const disabledDateFn2 = (date: Date) => {
  if (!!infoConfirmForm.produceTime && dayjs(date).valueOf() < dayjs(infoConfirmForm.produceTime).valueOf()) {
    return true;
  }
  return false;
};

const validate = async () => {
  if (!infoConfirmRef.value) return null;
  await infoConfirmRef.value?.validate();
  return getParams();
};

const getParams = () => {
  return { ...defaultParams, ...infoConfirmForm };
};

const init = () => {
  if (props.data) {
    defaultParams = { ...defaultParams, ...props.data };
  } else {
    return;
  }
  const {
    chemical = "",
    sumNum = "",
    drumANum = "",
    drumBNum = "",
    lotNumber = "",
    produceTime = "",
    validityTime = "",
    bucketCapacity = ""
  } = props.data;
  infoConfirmForm.chemical = chemical;
  infoConfirmForm.sumNum = sumNum;
  infoConfirmForm.drumANum = drumANum;
  infoConfirmForm.drumBNum = drumBNum;
  infoConfirmForm.lotNumber = lotNumber;
  infoConfirmForm.produceTime = produceTime;
  infoConfirmForm.validityTime = validityTime;
  infoConfirmForm.bucketCapacity = bucketCapacity;
};

onMounted(() => {
  init();
});

defineExpose({
  validate,
  getParams
});
</script>

<template>
  <px-collapse v-model="collapseValue">
    <px-collapse-item :name="collapseTitle">
      <template #title>
        <checkListTitle :title="collapseTitle" :noIndex="!!route.query.type" />
      </template>
      <div class="collapse-content-form">
        <px-form
          ref="infoConfirmRef"
          inline
          label-width="120px"
          :model="infoConfirmForm"
          :rules="infoConfirmRules"
          :disabled="realDisabled"
          scroll-to-error
          :scroll-into-view-options="{ behavior: 'smooth' }"
        >
          <px-row :gutter="32">
            <px-col :span="8">
              <px-form-item label="Chemical" prop="chemical">
                <px-select
                  v-model="infoConfirmForm.chemical"
                  clearable
                  filterable
                  remote
                  reserve-keyword
                  remote-show-suffix
                  :remote-method="remoteMethod"
                  :loading="chemicalLoading"
                  placeholder="请输入Chemical"
                >
                  <px-option v-for="item in chemicalOptions" :key="item" :label="item" :value="item" />
                </px-select>
              </px-form-item>
            </px-col>

            <px-col :span="8">
              <px-form-item label="合计数量" prop="sumNum">
                <px-input
                  v-model.trim.number="infoConfirmForm.sumNum"
                  class="px-input-number-no-controls"
                  type="number"
                  clearable
                  :min="0"
                  placeholder="请输入合计数量"
                />
              </px-form-item>
            </px-col>

            <px-col :span="8">
              <px-form-item label="Drum A" prop="drumANum">
                <px-input
                  v-model.trim.number="infoConfirmForm.drumANum"
                  class="px-input-number-no-controls"
                  type="number"
                  clearable
                  :min="0"
                  placeholder="请输入Drum A"
                />
              </px-form-item>
            </px-col>

            <px-col :span="8">
              <px-form-item label="Drum B" prop="drumBNum">
                <px-input
                  v-model.trim.number="infoConfirmForm.drumBNum"
                  class="px-input-number-no-controls"
                  type="number"
                  clearable
                  :min="0"
                  placeholder="请输入Drum B"
                />
              </px-form-item>
            </px-col>

            <px-col :span="8">
              <px-form-item label="Lot Number" prop="lotNumber">
                <px-input v-model.trim="infoConfirmForm.lotNumber" clearable placeholder="请输入Lot Number" />
              </px-form-item>
            </px-col>

            <px-col :span="8">
              <px-form-item label="生产日期" prop="produceTime">
                <px-date-picker
                  v-model="infoConfirmForm.produceTime"
                  clearable
                  type="date"
                  :editable="false"
                  :disabled-date="disabledDateFn"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择生产日期"
                />
              </px-form-item>
            </px-col>

            <px-col :span="8">
              <px-form-item label="有效期" prop="validityTime">
                <px-date-picker
                  v-model="infoConfirmForm.validityTime"
                  clearable
                  type="date"
                  :editable="false"
                  :disabled-date="disabledDateFn2"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择有效期"
                />
              </px-form-item>
            </px-col>

            <px-col :span="8">
              <px-form-item label="桶容量" prop="bucketCapacity">
                <px-input
                  v-model.trim.number="infoConfirmForm.bucketCapacity"
                  class="px-input-number-no-controls"
                  type="number"
                  clearable
                  :min="0"
                  placeholder="请输入桶容量"
                />
              </px-form-item>
            </px-col>
          </px-row>
        </px-form>
      </div>
    </px-collapse-item>
  </px-collapse>
</template>

<style lang="scss" scoped>
.px-collapse {
  margin-bottom: 16px;
  overflow: hidden;
  border-right: 1px solid var(--px-collapse-border-color);
  border-left: 1px solid var(--px-collapse-border-color);
  border-radius: 6px;

  :deep(.px-collapse-item) {
    > div {
      padding: 0 16px;

      &:nth-child(1) {
        background-color: rgb(248 248 248);
        border-bottom: 1px solid var(--px-collapse-border-color);

        .px-collapse-item__header {
          background-color: rgb(248 248 248);
          border-bottom: none;
        }
      }

      &:nth-child(2) {
        padding: 16px;
      }
    }

    .px-collapse-item__content {
      padding-bottom: 0;
    }

    .px-form-item {
      width: 100%;

      .px-form-item__content {
        .px-input-number .px-input__inner {
          text-align: left;
        }

        .px-select,
        .px-input,
        .px-input-number {
          width: 100%;
        }
      }
    }
  }
}
</style>
